package com.anti_poverty_detection_system.springboot.controller;

import com.anti_poverty_detection_system.springboot.mapper.HouseholdsMapper;
import com.anti_poverty_detection_system.springboot.mapper.UsersMapper;
import com.anti_poverty_detection_system.springboot.model.Households;
import com.anti_poverty_detection_system.springboot.model.Regions;
import com.anti_poverty_detection_system.springboot.model.Users;
import com.anti_poverty_detection_system.springboot.service.IHouseholdsService;
import com.anti_poverty_detection_system.springboot.service.IRegionsService;
import com.anti_poverty_detection_system.springboot.service.IUsersService;
import com.anti_poverty_detection_system.springboot.service.dto.HouseholdAndUserRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ZITONG BAI
 * @since 2024-06-17
 */
@RestController
@RequestMapping("/households")
public class HouseholdsController {
    @Autowired
    IUsersService usersService;
    @Autowired
    IHouseholdsService householdsService;
    @Autowired
    IRegionsService regionsService;


    private final ObjectMapper objectMapper = new ObjectMapper();
    @PostMapping("/add_household_info")
    public ResponseEntity<String> addHouseholdInfo(@RequestBody String info) {
        try {
            // 解析JSON数据
            JsonNode jsonNode = objectMapper.readTree(info);
            String username = jsonNode.get("username").asText();
            String region = jsonNode.get("address").asText();
            String[] parts = region.split(",");
            String village = String.join(",", Arrays.copyOfRange(parts, 1, parts.length));
            int userId = usersService.getUserByUsername(username).getUserId();
            Users users = usersService.getUserByUsername(username);
            users.setRegion(regionsService.getRegionsByVillage(village).getRegionName());
            usersService.saveOrUpdate(users);

            // 获取 Households 对象
            Households households = householdsService.getHouseholdsByUsers(userId);

            // 如果记录存在，则更新；否则插入新记录
            if (households != null) {
                households.setPersonalInfo(info);
                households.setPovertyStatus(jsonNode.get("povertyStatus").asText());

            } else {
                households = new Households();
                households.setPersonalInfo(info);
                households.setPovertyStatus(jsonNode.get("povertyStatus").asText());
                households.setUserId(userId);
            }
            householdsService.saveOrUpdate(households);
            return ResponseEntity.ok("上传信息成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @PostMapping("/get_household")
    public ResponseEntity<String> getHousehold(@RequestBody Users users){
        // 获取对应农户家庭信息
        Households households=householdsService.getHouseholdsByUsers(usersService.getUserByUsername(users.getUsername()).getUserId());
        // 返回农户信息
        return ResponseEntity.ok().body(households.getPersonalInfo());
    }
    @GetMapping("get_households_and_users")
    public ResponseEntity<Page<HouseholdAndUserRequest>> getHouseholdsAndUsers(
            @RequestParam("region_name") String regionName,
            @RequestParam int page,
            @RequestParam int size,
            @RequestParam(required = false) String keywords
    ) {
        // 按照行政区和role来找用户
        Page<Users> usersPage = new Page<>(page, size);
        QueryWrapper<Users> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("region", regionName).eq("role", 1);
        // 关键词模糊搜索
        if (keywords != null && !keywords.trim().isEmpty()) {
            userQueryWrapper.and(wrapper -> wrapper.like("real_name", keywords).or().like("region", keywords));
        }
        // 分页查询用户
        Page<Users> usersPage1 = usersService.page(usersPage,userQueryWrapper);
        List<Users> filteredUsers  = usersPage1.getRecords();
        if (filteredUsers.isEmpty()) {
            // 如果没有符合条件的用户，返回空结果
            return ResponseEntity.ok(new Page<>(page, size, 0));
        }
        // 获取用户ID列表
        List<Integer> userIds = filteredUsers.stream().map(Users::getUserId).collect(Collectors.toList());
        // 构建农户家庭筛选条件
        QueryWrapper<Households> householdWrapper = new QueryWrapper<>();
        householdWrapper.in("user_id", userIds);
        // 分页查询家庭
        Page<Households> householdPage = new Page<>(page, size);
        Page<Households> householdResultPage = householdsService.page(householdPage, householdWrapper);
        List<Households> filteredHouseholds = householdResultPage.getRecords();
        // 创建结果对象列表
        List<HouseholdAndUserRequest> resultList = new ArrayList<>();
        for (Households household : filteredHouseholds) {
            Users user = filteredUsers.stream().filter(u -> u.getUserId().equals(household.getUserId())).findFirst().orElse(null);
            if (user != null && "poor".equals(household.getPovertyStatus())) {
                HouseholdAndUserRequest request = new HouseholdAndUserRequest();
                request.setRealName(user.getRealName());
                request.setRegion(user.getRegion());
                request.setPovertyStatus(household.getPovertyStatus());
                resultList.add(request);
            }

        }
        // 构建结果分页对象
        Page<HouseholdAndUserRequest> resultPage = new Page<>(page, size, householdResultPage.getTotal());
        resultPage.setRecords(resultList);

        return ResponseEntity.ok(resultPage);
    }
    @PostMapping("delete_households")
    public ResponseEntity<String> deleteHouseholds(@RequestBody Users users) {
        // 根据用户名查找用户
        Users users1 = usersService.getUserByUsername(users.getUsername());
        if (users1 == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("用户未找到");
        }

        // 根据用户ID查找相关的家庭
        Households households = householdsService.getHouseholdsByUsers(users1.getUserId());
        if (households != null) {
            // 删除家庭
            householdsService.removeById(households.getHouseholdId());
        }

        // 删除用户
        usersService.removeById(users1.getUserId());

        return ResponseEntity.ok("删除成功");
    }

}
